package org.mch.func.file.filename;

import java.awt.event.MouseEvent;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

import org.mch.biz.ui.BizEvent;
import org.mch.biz.ui.BizPanel;
import org.mch.main.MCHFrame;
import org.mch.swingm.core.MFileChooser;

/**
 * 描述：文件操作；
 * 
 * @author MCHUN；
 * 
 */
public class ClientEvent extends BizEvent {
	private static final long serialVersionUID = -8590108060646853821L;

	private MFileChooser fileChooser;
	private MFileNameUtils fileNameUtils;

	public ClientEvent(BizPanel panel) {
		super(panel);
	}

	protected void buttonClicked(MouseEvent e) throws Exception {
		if (e.getSource() == getPanel().getBtnExecute()) {
			execute();
		}
	}

	public void execute() {
		if (getPanel().getSelAddFileNamePrefix().isSelected()) {
			// 增加，前缀
			String filePath = getPanel().getFile_path().getValue();
			String prefix = getPanel().getTextFileNamePrefix().getText();
			boolean isFileAndFolderName = getPanel().getIsFileAndFolderName().isSelected();// 是否包含文件夹
			getFileNameUtils().addNamePrefix(filePath, prefix, isFileAndFolderName);

		} else if (getPanel().getSelAddFileNameSuffix().isSelected()) {
			// 增加，后缀
			String filePath = getPanel().getFile_path().getValue();
			String suffix = getPanel().getTextFileNameSuffix().getText();
			boolean isFileAndFolderName = getPanel().getIsFileAndFolderName().isSelected();// 是否包含文件夹
			getFileNameUtils().addNameSuffix(filePath, suffix, isFileAndFolderName);

		} else if (getPanel().getRdbtn_oldnew().isSelected()) {
			boolean isUpdateFloder = getPanel().getCheck_floder().isSelected();// 是否修改文件夹名
			boolean isSearchChild = getPanel().getCheck_searchchild().isSelected();// 是否搜索子文件夹

			// 要更新的 文件夹
			String folderPath = getPanel().getFile_path().getValue();

			String tmp_reqgz = getPanel().getText_repgz().getText();
			String[] reqgzss = tmp_reqgz.split("\n");

			for (String reqgz : reqgzss) {
				String[] ss = reqgz.split("=");
				String old_str = ss[0];
				if (old_str == null) {
					continue;
				}
				String new_str = ss.length == 1 || ss[1] == null ? "" : ss[1];
				getFileNameUtils().reqlaceFileName(old_str, new_str, new File(folderPath), isUpdateFloder, isSearchChild);
			}

		} else if (getPanel().getRdbtn_zdwjfolder().isSelected()) {
			// 将指定目录下，所有文件夹下，指定的文件类型的文件名改为与其所在文件夹相同

			String filepath = getPanel().getFile_path().getValue();
			File file = new File(filepath);
			File[] files = file.listFiles();

			Map<File, File> fileRenameMap = new HashMap<File, File>();

			String fileType = getPanel().getText_filetype().getText();

			for (File tmpfile : files) {
				if (tmpfile.isDirectory()) {
					// 如果是文件夹，就看看此文件下是否有文件
					File[] childfiles = tmpfile.listFiles();
					for (File childTmpFile : childfiles) {
						if (childTmpFile.getName().toLowerCase().endsWith(fileType.toLowerCase())) {
							reNameFileName(childTmpFile, tmpfile.getName());
						}
					}
				}
			}

			getFileNameUtils().renameFileMap(fileRenameMap);
		} else if (getPanel().getRdbtn_filefoldercount().isSelected()) {
			// 统计目录下，文件和文件夹个数
			long fileCount = 0L;
			String filepath = getPanel().getFile_path().getValue();
			File file = new File(filepath);
			File[] files = file.listFiles();
			fileCount = sumFileFolderCount(files);
			getPanel().getText_filefolder_count().setText(fileCount + "");
		} else if (getPanel().getRdbtn_filetypeedit().isSelected()) {
			editFileType();
		} else {
			JOptionPane.showMessageDialog(MCHFrame.frame, "请选择要执行的操作！");
		}
	}

	private void editFileType() {
		String filepath = getPanel().getFile_path().getValue();
		File file = new File(filepath);
		String oldTypeName = getPanel().getText_oldfiletype().getText();
		String newTypeName = getPanel().getText_newfiletype().getText();
		getFileNameUtils().editFileType(file, oldTypeName, newTypeName);
	}

	protected long sumFileFolderCount(File[] files) {
		if (files == null || files.length == 0) {
			return 0L;
		}

		long count = 0;
		boolean isSelectFile = getPanel().getChx_baohanfile().isSelected();
		boolean isSelectFolder = getPanel().getChx_baohanfolder().isSelected();
		boolean isSelectFileHide = getPanel().getChx_baohanfilehide().isSelected();
		boolean isSelectFolderHide = getPanel().getChx_baohanfolderhide().isSelected();
		boolean isSelectFolderChild = getPanel().getChx_baohanfolderchild().isSelected();

		for (int i = 0, len = files.length; i < len; i++) {
			File tmpfile = files[i];
			if (tmpfile.isDirectory()) {
				if (tmpfile.isHidden()) {
					if (isSelectFolderHide) {
						if (isSelectFolderChild) {// 包含子目录
							count += sumFileFolderCount(tmpfile.listFiles());
						}
					}
				} else {
					if (isSelectFolderChild) {// 包含子目录
						count += sumFileFolderCount(tmpfile.listFiles());
					}
				}
				if (isSelectFolder) {
					count++;
				}
			} else if (tmpfile.isFile() && isSelectFile) {
				if (tmpfile.isHidden()) {
					if (isSelectFileHide) {
						count++;
					}
				} else {
					count++;
				}
			}
		}

		return count;
	}

	protected void reNameFileName(File file, String newName) {
		reNameFileName(file, newName, null);
	}

	/**
	 * 修改文件名，支持文件或文件夹
	 * 
	 * @param file
	 * @param newName
	 */
	protected void reNameFileName(File file, String newName, String fileType) {
		String oldpath = file.getPath();

		if (file.isDirectory()) {
			// 如果是文件夹，进行如下修改
			String newpath = oldpath.substring(0, oldpath.lastIndexOf(File.separator)) + File.separator + newName;
			File newfile = new File(newpath);
			file.renameTo(newfile);
		} else if (file.isFile()) {
			// 如果是文件，进行如下修改
			String filename = file.getName();
			if (filename.indexOf(".") > 0) {
				String fix = null;
				if (fileType == null || fileType.trim().equals("")) {
					fix = filename.substring(filename.lastIndexOf("."), filename.length());
				} else {
					fix = fileType;
				}
				String folderpath = oldpath.substring(0, oldpath.lastIndexOf(File.separator));
				String newpath = folderpath + File.separator + newName + fix;
				File newfile = new File(newpath);
				file.renameTo(newfile);
			} else {
				String newpath = oldpath.substring(0, oldpath.lastIndexOf(File.separator)) + File.separator + newName;
				File newfile = new File(newpath);
				file.renameTo(newfile);
			}
		} else {

		}

	}

	public void browse() {
		int tmp = getFileChooser().showOpenDialog(MCHFrame.getFrame());
		if (tmp == JFileChooser.APPROVE_OPTION) {
			getPanel().getFile_path().setText(getFileChooser().getSelectedFile().getPath());
		}
	}

	public MFileChooser getFileChooser() {
		if (fileChooser == null) {
			fileChooser = new MFileChooser();
			fileChooser.setPreferredSize(700, 400);
			fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);// 设置能选择文件和文件夹
		}
		return fileChooser;
	}

	public MFileNameUtils getFileNameUtils() {
		if (fileNameUtils == null) {
			fileNameUtils = new MFileNameUtils();
		}
		return fileNameUtils;
	}

	public ClientPanel getPanel() {
		return (ClientPanel) super.getPanel();
	}
}